import Controller from "../Controller";
import {Request,Response} from 'express';
import Fs from 'fs-extra'
import path from "path";
import Config from "../../Config";
import PageJson from "../../utils/PageJson";
/**
 * 全局配置
 */
class GlobalStyle extends Controller
{
    // 模板id
    tpl_id:number = 0;

    constructor(req:Request,res:Response) {
        super(req,res);
        this.tpl_id = this.HD.tpl_id;
    }

    /**
     * 获取全局配置  配置文件page.json
     */
    async get() {
        const {dir} = await this.first("tpl",{
            id: this.tpl_id
        }) as { dir:string }
        this.response(200,PageJson.get(dir,"globalStyle"))
    }

    /**
     * 提交生成配置文件page.json
     */
    async submit() {
        // 获取模板信息
        const tpl = await this.first("tpl",{
            id: this.tpl_id
        }) as { dir:string }
        const pages_json_path = path.join(Config.data_dir,tpl.dir,'src','pages.json')
        const pagesData = Fs.readJsonSync(pages_json_path);
        pagesData.globalStyle = this.HD.data
        this.setBackground(tpl.dir,this.HD.data.backgroundColor)
        Fs.writeJSONSync(pages_json_path,pagesData); 
        this.response(200)
    }

    /**
     * 设置全局背景页面
     * @param dir 项目目录路径
     * @param color 十六进制背景颜色
     */
    setBackground(dir:string,color:string) {
        const app_vue_path = path.join(Config.data_dir,dir,'src','App.vue')
        let app_vue_content = Fs.readFileSync(app_vue_path,"utf-8")
        app_vue_content = app_vue_content.replace(/background-color: #.{6};/g,`background-color: ${color};`)
        Fs.writeFileSync(app_vue_path,app_vue_content,"utf-8")
    }
}

export default GlobalStyle;